from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QPushButton, 
                           QLabel, QFileDialog, QProgressBar,
                           QListWidget, QHBoxLayout, QMessageBox,
                           QCheckBox, QFrame, QListWidgetItem)
from PyQt6.QtCore import Qt, pyqtSignal, QObject
from PyQt6.QtGui import QFont, QIcon
import pandas as pd
import os
from datetime import datetime

class SignalEmitter(QObject):
    progress_signal = pyqtSignal(int)
    error_signal = pyqtSignal(str)
    complete_signal = pyqtSignal()

class SheetListWidget(QListWidget):
    """自定义sheet列表控件"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSelectionMode(QListWidget.SelectionMode.MultiSelection)
        self.setStyleSheet("""
            QListWidget {
                border: 1px solid #CCCCCC;
                border-radius: 4px;
                padding: 5px;
                background: white;
            }
            QListWidget::item {
                padding: 8px 12px;
                margin: 2px 5px;
                border: 1px solid #E0E0E0;
                border-radius: 4px;
                background: #FFFFFF;
            }
            QListWidget::item:selected {
                background: #ECF2FF;
                border: 1px solid #2B579A;
            }
            QListWidget::item:hover:!selected {
                background: #F5F8FF;
                border: 1px solid #A8C0FF;
            }
            QListWidget::item {
                color: #2B579A;  /* Sheet名称的颜色 */
                font-weight: bold;
            }
        """)

    def addSheetItem(self, sheet_name, sheet_info):
        """添加自定义的工作表项"""
        item = QListWidgetItem()
        item.setData(Qt.ItemDataRole.UserRole, sheet_name)  # 存储工作表名称
        
        # 设置显示文本
        display_text = f"{sheet_name}  ({sheet_info})"
        item.setText(display_text)
        
        # 添加到列表
        self.addItem(item)

class ExcelConverterWidget(QWidget):
    def __init__(self, title="Excel转Markdown", description="将Excel文件转换为Markdown表格"):
        super().__init__()
        self.title = title
        self.description = description
        self.excel_file = None
        self.save_path = None
        self.sheets = []
        
        # 创建信号发射器
        self.signal_emitter = SignalEmitter()
        self.signal_emitter.progress_signal.connect(self.on_progress_update)
        self.signal_emitter.error_signal.connect(self.on_error)
        self.signal_emitter.complete_signal.connect(self.on_conversion_complete)
        
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题和说明
        title = QLabel(self.title)
        title.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        layout.addWidget(title)
        
        desc = QLabel(self.description)
        desc.setStyleSheet("color: #666666;")
        layout.addWidget(desc)
        
        # 文件选择区域
        file_area = QHBoxLayout()
        self.select_btn = QPushButton("选择Excel")
        self.select_btn.setStyleSheet("""
            QPushButton {
                background-color: #2B579A;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #1E3F7F;
            }
        """)
        self.select_btn.clicked.connect(self.select_file)
        file_area.addWidget(self.select_btn)
        
        self.file_label = QLabel("未选择文件")
        self.file_label.setStyleSheet("color: #666666;")
        file_area.addWidget(self.file_label)
        file_area.addStretch()
        layout.addLayout(file_area)
        
        # Sheet列表
        sheet_frame = QFrame()
        sheet_frame.setStyleSheet("""
            QFrame {
                border: 1px solid #CCCCCC;
                border-radius: 4px;
                background: white;
            }
        """)
        sheet_layout = QVBoxLayout(sheet_frame)
        
        sheet_header = QHBoxLayout()
        sheet_label = QLabel("工作表")
        sheet_label.setFont(QFont("Arial", 11, QFont.Weight.Bold))
        sheet_header.addWidget(sheet_label)
        
        self.select_all_cb = QCheckBox("全选")
        self.select_all_cb.stateChanged.connect(self.toggle_all_sheets)
        sheet_header.addWidget(self.select_all_cb)
        sheet_layout.addLayout(sheet_header)
        
        self.sheet_list = SheetListWidget()
        sheet_layout.addWidget(self.sheet_list)
        
        layout.addWidget(sheet_frame)
        
        # 保存路径选择
        save_area = QHBoxLayout()
        self.save_path_label = QLabel("未选择保存位置")
        self.save_path_label.setStyleSheet("color: #666666;")
        save_area.addWidget(self.save_path_label)
        
        self.save_btn = QPushButton("选择路径")
        self.save_btn.setStyleSheet("""
            QPushButton {
                background-color: #2B579A;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #1E3F7F;
            }
        """)
        self.save_btn.clicked.connect(self.select_save_path)
        save_area.addWidget(self.save_btn)
        layout.addLayout(save_area)
        
        # 转换按钮
        convert_area = QHBoxLayout()
        convert_area.addStretch()
        self.convert_btn = QPushButton("转换为Markdown")
        self.convert_btn.setMinimumWidth(120)
        self.convert_btn.setStyleSheet("""
            QPushButton {
                background-color: #2B579A;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #1E3F7F;
            }
            QPushButton:disabled {
                background-color: #CCCCCC;
            }
        """)
        self.convert_btn.clicked.connect(self.start_convert)
        self.convert_btn.setEnabled(False)
        convert_area.addWidget(self.convert_btn)
        layout.addLayout(convert_area)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 1px solid #CCCCCC;
                border-radius: 4px;
                text-align: center;
            }
            QProgressBar::chunk {
                background-color: #2B579A;
            }
        """)
        self.progress_bar.hide()
        layout.addWidget(self.progress_bar)
        
        # 状态标签
        self.status_label = QLabel("")
        self.status_label.setStyleSheet("color: #666666;")
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.status_label)
        
        layout.addStretch()

    def select_file(self):
        """选择Excel文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择Excel文件",
            "",
            "Excel文件 (*.xlsx *.xls)"
        )
        if file_path:
            try:
                # 读取Excel文件
                excel = pd.ExcelFile(file_path)
                self.excel_file = file_path
                self.sheets = excel.sheet_names
                
                # 更新文件名显示
                self.file_label.setText(os.path.basename(file_path))
                
                # 更新sheet列表
                self.sheet_list.clear()
                for sheet_name in self.sheets:
                    # 读取工作表信息
                    df = pd.read_excel(file_path, sheet_name=sheet_name)
                    sheet_info = f"{len(df)} 行 × {len(df.columns)} 列"
                    self.sheet_list.addSheetItem(sheet_name, sheet_info)
                
                # 设置默认保存路径
                self.save_path = os.path.dirname(file_path)
                self.save_path_label.setText(f"保存位置: {self.save_path}")
                
                # 自动选择第一个工作表
                if self.sheet_list.count() > 0:
                    self.sheet_list.item(0).setSelected(True)
                
                self.status_label.setText("请选择要转换的工作表")
                self.update_convert_button()
                
            except Exception as e:
                QMessageBox.critical(
                    self,
                    "错误",
                    f"无法打开Excel文件：{str(e)}"
                )

    def select_save_path(self):
        """选择保存位置"""
        path = QFileDialog.getExistingDirectory(
            self,
            "选择保存位置",
            "",
            QFileDialog.Option.ShowDirsOnly
        )
        if path:
            self.save_path = path
            self.save_path_label.setText(f"保存位置: {path}")
            self.update_convert_button()

    def toggle_all_sheets(self, state):
        """切换全选状态"""
        for i in range(self.sheet_list.count()):
            item = self.sheet_list.item(i)
            item.setSelected(state == Qt.CheckState.Checked.value)

    def update_convert_button(self):
        """更新转换按钮状态"""
        # 只要有Excel文件和选中的工作表就可以启用转换按钮
        self.convert_btn.setEnabled(
            bool(self.excel_file) and 
            bool(self.sheet_list.selectedItems())
        )

    def start_convert(self):
        """开始转换"""
        if not self.excel_file or not self.save_path:
            return
            
        # 获取选中的工作表名称
        selected_sheets = []
        for item in self.sheet_list.selectedItems():
            sheet_name = item.data(Qt.ItemDataRole.UserRole)
            if sheet_name:
                selected_sheets.append(sheet_name)
            
        if not selected_sheets:
            return
            
        try:
            # 生成输出文件名
            base_name = os.path.basename(self.excel_file)
            name_without_ext = os.path.splitext(base_name)[0]
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_file = os.path.join(
                self.save_path, 
                f"{name_without_ext}_{timestamp}.md"
            )
            
            # 禁用按钮
            self.convert_btn.setEnabled(False)
            self.select_btn.setEnabled(False)
            self.save_btn.setEnabled(False)
            self.progress_bar.show()
            self.progress_bar.setValue(0)
            self.status_label.setText("正在转换...")
            
            # 读取Excel文件
            excel = pd.ExcelFile(self.excel_file)
            total_sheets = len(selected_sheets)
            
            with open(output_file, 'w', encoding='utf-8') as f:
                for i, sheet_name in enumerate(selected_sheets):
                    # 读取工作表
                    df = pd.read_excel(self.excel_file, sheet_name=sheet_name)
                    
                    # 写入Markdown
                    f.write(f"# {sheet_name}\n\n")
                    f.write(df.to_markdown(index=False))
                    f.write("\n\n")
                    
                    # 更新进度
                    progress = int((i + 1) / total_sheets * 100)
                    self.signal_emitter.progress_signal.emit(progress)
            
            self.signal_emitter.complete_signal.emit()
            
        except Exception as e:
            self.signal_emitter.error_signal.emit(str(e))

    def on_progress_update(self, value):
        """处理进度更新"""
        self.progress_bar.setValue(value)

    def on_error(self, error_message):
        """处理错误"""
        QMessageBox.critical(
            self,
            "转换错误",
            f"转换过程中发生错误：\n{error_message}"
        )
        self.reset_interface()

    def on_conversion_complete(self):
        """处理转换完成"""
        QMessageBox.information(
            self,
            "转换完成",
            f"Excel已成功转换为Markdown！\n保存位置：{self.save_path}"
        )
        self.reset_interface()

    def reset_interface(self):
        """重置界面"""
        self.progress_bar.hide()
        self.status_label.setText("")
        self.convert_btn.setEnabled(True)
        self.select_btn.setEnabled(True)
        self.save_btn.setEnabled(True) 